import { message } from 'antd';
import { Order, OrderStatus } from '../types/order';

// 从 localStorage 获取订单列表
const getStoredOrders = (): Order[] => {
  const ordersStr = localStorage.getItem('orders');
  if (!ordersStr) return [];
  try {
    return JSON.parse(ordersStr);
  } catch {
    return [];
  }
};

// 保存订单列表到 localStorage
const saveOrders = (orders: Order[]) => {
  localStorage.setItem('orders', JSON.stringify(orders));
};

// 获取所有订单
export const getAllOrders = async (): Promise<Order[]> => {
  return getStoredOrders();
};

// 创建订单
export const createOrder = async (order: Omit<Order, 'id' | 'createTime'>): Promise<Order> => {
  console.log('=== 开始创建订单 ===');
  const orders = getStoredOrders();
  const newOrder: Order = {
    ...order,
    id: `ORDER${Date.now()}`,  // 生成唯一的订单ID
    createTime: new Date().toISOString(),
    paymentMethod: order.paymentMethod || 'alipay'  // 确保有默认值
  };
  console.log('创建的新订单:', newOrder);
  
  orders.push(newOrder);
  saveOrders(orders);
  console.log('订单已保存到 localStorage');
  
  // 验证保存是否成功
  const savedOrders = getStoredOrders();
  console.log('验证保存后的订单列表:', savedOrders);
  
  message.success('订单创建成功');
  console.log('=== 订单创建完成 ===');
  return newOrder;
};

// 删除订单
export const deleteOrder = async (orderId: string): Promise<void> => {
  const orders = getStoredOrders();
  const index = orders.findIndex(order => order.id === orderId);
  if (index === -1) {
    message.error('订单不存在');
    return;
  }
  orders.splice(index, 1);
  saveOrders(orders);
  message.success('订单删除成功');
};

// 更新订单状态
export const updateOrderStatus = async (orderId: string, status: OrderStatus, paymentMethod?: string): Promise<Order> => {
  console.log('=== 开始更新订单状态 ===');
  console.log('订单ID:', orderId);
  console.log('目标状态:', status);
  console.log('支付方式:', paymentMethod);
  
  const orders = getStoredOrders();
  console.log('当前所有订单:', orders);
  
  const orderIndex = orders.findIndex(order => order.id === orderId);
  console.log('找到的订单索引:', orderIndex);
  
  if (orderIndex === -1) {
    console.error('找不到订单:', orderId);
    throw new Error('订单不存在');
  }
  
  // 更新订单状态
  const order = orders[orderIndex];
  console.log('更新前的订单状态:', order.status);
  console.log('更新前的支付方式:', order.paymentMethod);
  
  // 更新订单状态
  order.status = status;
  console.log('更新后的订单状态:', order.status);
  
  // 如果是支付完成，记录支付时间和支付方式
  if (status === OrderStatus.PAID) {
    order.payTime = new Date().toISOString();
    if (paymentMethod) {
      order.paymentMethod = paymentMethod;
    }
    console.log('记录支付时间:', order.payTime);
    console.log('记录支付方式:', order.paymentMethod);
  }
  
  // 保存更新后的订单列表
  saveOrders(orders);
  console.log('订单列表已保存到 localStorage');
  
  // 验证保存是否成功
  const savedOrders = getStoredOrders();
  console.log('验证保存后的订单列表:', savedOrders);
  
  message.success('订单状态更新成功');
  console.log('=== 订单状态更新完成 ===');
  return order;
};

// 获取订单详情
export const getOrderById = async (orderId: string): Promise<Order | undefined> => {
  const orders = getStoredOrders();
  return orders.find(order => order.id === orderId);
}; 